/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.mzb.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.*;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.mzb.entity.MzbUnitinfo;
import com.thinkgem.jeesite.modules.mzb.entity.MzbYearcheck;
import com.thinkgem.jeesite.modules.mzb.service.MzbUnitinfoService;
import com.thinkgem.jeesite.modules.mzb.service.MzbYearcheckService;
import com.thinkgem.jeesite.modules.oa.entity.OaNotify;
import com.thinkgem.jeesite.modules.oa.entity.OaNotifyRecord;
import com.thinkgem.jeesite.modules.oa.service.OaNotifyService;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.security.SystemAuthorizingRealm;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.weixin.utils.NoticeTemplateMsgUtil;
import com.thinkgem.jeesite.weixin.utils.ResultTemplateMsgUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 用于提交年检申报的信息Controller
 *
 * @author chenww
 * @version 2016-09-13
 */
@Controller
@RequestMapping(value = "${adminPath}/mzb/mzbYearcheck")
public class MzbYearcheckController extends BaseController {

    @Autowired
    private MzbYearcheckService mzbYearcheckService;


    @Autowired
    private MzbUnitinfoService mzbUnitinfoService;

    @Autowired
    private OaNotifyService oaNotifyService;

    //业务申报通知
    @Autowired
    private NoticeTemplateMsgUtil noticeTemplateMsgUtil;

    //审核结果通知
    @Autowired
    private ResultTemplateMsgUtil resultTemplateMsgUtil;

    @ModelAttribute
    public MzbYearcheck get(@RequestParam(required = false) String id) {
        MzbYearcheck entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = mzbYearcheckService.get(id);
        }

        if (entity == null) {
            entity = new MzbYearcheck();
        }
        return entity;
    }

    @RequiresPermissions("mzb:mzbYearcheck:view")
    @RequestMapping(value = {"list", ""})
    public String list(MzbYearcheck mzbYearcheck, HttpServletRequest request, HttpServletResponse response, Model model) {
        //如果是手机端提交的就跳转
        String abc = request.getParameter("model");
        if (StringUtils.isNotBlank(abc)) {
            return "modules/mzb/njsb_section";
        }

        Page<MzbYearcheck> page = mzbYearcheckService.findPage(new Page<MzbYearcheck>(request, response), mzbYearcheck);
        model.addAttribute("page", page);
        return "modules/mzb/mzbYearcheckList";
    }


    @RequiresPermissions("mzb:mzbYearcheck:view")
    @RequestMapping(value = "uncheck")
    public String uncheck(MzbYearcheck mzbYearcheck, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {


        //本年公示查询
//        mzbYearcheck.setStatus("1");
        // mzbYearcheck.setStatus("12");
        //查询当前用户下创建的基本信息
        mzbYearcheck.getSqlMap().put("dsf", BaseService.dataScopeFilter(mzbYearcheck.getCurrentUser(), "o", "u"));
        Page<MzbYearcheck> page = mzbYearcheckService.findPage(new Page<MzbYearcheck>(request, response), mzbYearcheck);
        //判断当前用户是否已提交了基本信息,有:正常跳转,无:跳到基本信息表单填写.
        MzbUnitinfo mzbUnitinfo = mzbUnitinfoService.findByCreatUserId(UserUtils.getUser().getId());
        model.addAttribute("page", page);
//        model.addAttribute("isOld",false);
//      response.sendRedirect("mzb/mzbUnitinfo");

            //判断是否从手机端过来的
            SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
            if (principal.isMobileLogin()) {
                return "modules/mzb/njsb_section";
            }else{
                if (mzbUnitinfo == null) {
                    model.addAttribute("hasWri", false);
                } else {
                    model.addAttribute("hasWri", true);
            }
                return "modules/mzb/mzbYearcheckList";

        }


    }

    /**
     * 导出数据
     * @param mzbYearcheck
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("mzb:mzbYearcheck:view")
    @RequestMapping(value = "export", method= RequestMethod.POST)
    public String exportFile(MzbYearcheck mzbYearcheck, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "用户数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<MzbYearcheck> page = mzbYearcheckService.findPage(new Page<MzbYearcheck>(request, response, -1), mzbYearcheck);
            new ExportExcel("用户数据", MzbYearcheck.class).setDataList(page.getList()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出用户失败！失败信息："+e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/mzb/mzbYearcheck/uncheck?repage";
    }

//    @RequiresPermissions("mzb:mzbYearcheck:view")
//    @RequestMapping(value = "check")
//    public String check(MzbYearcheck mzbYearcheck, HttpServletRequest request, HttpServletResponse response, Model model) {
////        mzbYearcheck.setStatus("0");
//        mzbYearcheck.getSqlMap().put("dsf", BaseService.dataScopeFilter(mzbYearcheck.getCurrentUser(), "o", "u"));
//        Page<MzbYearcheck> page = mzbYearcheckService.findPage(new Page<MzbYearcheck>(request, response), mzbYearcheck);
//        model.addAttribute("page", page);
//        model.addAttribute("isOld",true);
//        return "modules/mzb/mzbYearcheckList";
//    }


    //获取社会组织往年的json
    @RequiresPermissions("mzb:mzbYearcheck:view")
    @RequestMapping(value = "getListJson")
    public void getListJson(MzbYearcheck mzbYearcheck, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        mzbYearcheck.setStatus("0");
        mzbYearcheck.getSqlMap().put("dsf", BaseService.dataScopeFilter(mzbYearcheck.getCurrentUser(), "o", "u"));
        Page<MzbYearcheck> page = mzbYearcheckService.findPage(new Page<MzbYearcheck>(request, response), mzbYearcheck);
        JSONArray array = new JSONArray();
        //查询当前用户下创建的基本信息
        for (MzbYearcheck mzbYearcheck1 : page.getList()) {
            JSONObject json = new JSONObject();
            json.put("name",mzbYearcheck1.getCreateBy().getName());
            json.put("id", mzbYearcheck1.getId());
            json.put("createDate", mzbYearcheck1.getCreateDate());
            array.add(json);
        }
        PrintWriter out = response.getWriter();
        out.print(array);
    }

    @RequiresPermissions("mzb:mzbYearcheck:view")
    @RequestMapping(value = "form")
    public String form(MzbYearcheck mzbYearcheck, Model model, RedirectAttributes redirectAttributes) {
        model.addAttribute("mzbYearcheck", mzbYearcheck);
        MzbUnitinfo mzbUnitinfo = mzbUnitinfoService.findByCreatUserId(UserUtils.getUser().getId());
        if (mzbUnitinfo == null && !SecurityUtils.getSubject().isPermitted("mzb:mzbYearcheck:admin")) {
            addMessage(redirectAttributes, "请先填写基本信息,才能申报!");
            return "redirect:" + Global.getAdminPath() + "/mzb/mzbYearcheck/uncheck?repage";
        }
        return "modules/mzb/mzbYearcheckForm";
    }

    //年检申报审批查看
    @RequiresPermissions("mzb:mzbYearcheck:view")
    @RequestMapping(value = "view")
    public String view(MzbYearcheck mzbYearcheck, Model model) {

        model.addAttribute("mzbYearcheck", mzbYearcheck);
        //判断是否从手机端过来的
        SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
        if (principal.isMobileLogin()) {
            return "modules/mzb/mzbYearcheck_view_section";
        }
        return "modules/mzb/mzbYearcheckView";
    }


    @RequiresPermissions("mzb:mzbYearcheck:edit")
    @RequestMapping(value = "save")
    public String save(MzbYearcheck mzbYearcheck, Model model, RedirectAttributes redirectAttributes) {
        User recordUser = new User();
        if (SecurityUtils.getSubject().isPermitted("mzb:mzbYearcheck:admin")){
            recordUser = UserUtils.get(mzbYearcheck.getCreateBy().getId());
        }

        String openid  = StringUtils.isEmpty(recordUser.getOpenid()) ? "" : recordUser.getOpenid();
        if (!beanValidator(model, mzbYearcheck)) {
            return form(mzbYearcheck, model,redirectAttributes);
        }

        //发送审核中的通知
        if (StringUtils.isBlank(mzbYearcheck.getStatus())) {
            mzbYearcheck.setStatus("1");
        }

        //发送审核中的通知
//        if (StringUtils.equals(mzbYearcheck.getStatus(),"2")) {
//
//            resultTemplateMsgUtil.send2Word(openid, recordUser.getName() + "的经办人,您好,您提交的材料工作人员正在审核中.","年检申报", DictUtils.getDictLabel("2", "check_flag", ""),"审批意见:" + mzbYearcheck.getRemarks());
//        }

        //发送审核通过的通知
        if (StringUtils.equals(mzbYearcheck.getStatus(),"3")) {
            //获取创建用户的id
            String userId = mzbYearcheck.getCreateBy().getId();
            User user = UserUtils.get(userId);

            //生成对应的报告书
            Map paramMap = new HashMap();
            String num = mzbYearcheckService.findPassCount();
            String count = num;//通过查询通过审核的个数
            String num1 = "" ;
            if(StringUtils.isBlank(count)){
                 num1 = DateUtils.formatDate(new Date(), "yyyyMMddhhmmss") + "_" + 0;}else {num1 = DateUtils.formatDate(new Date(), "yyyyMMddhhmmss") + "_" + count;
            }





            //申请单位
            String unit = user.getName();
            MzbUnitinfo mzbUnitinfo = mzbUnitinfoService.findByCreatUserId(userId);
            //申请单位经办人
            String jbr = mzbUnitinfo.getJbrmz();
            //经办人手机
            String sj = mzbUnitinfo.getJbrsj();
            //经办人身份证号
            String sfz = mzbUnitinfo.getJbrsfz();
            //预审通过时间
            String passDate = DateUtils.formatDate(mzbYearcheck.getUpdateDate(), "yyyy-MM-dd");

            paramMap.put("num", num1);//业务编号
            paramMap.put("unit", unit);
            paramMap.put("jbr", jbr);
            paramMap.put("sj", sj);
            paramMap.put("sfz", sfz);
            paramMap.put("passDate", passDate);

            String fileName = DateUtils.formatDate(new Date(), "yyyyMMddhhmmss");
            genPdfFile(fileName,paramMap);



            //创建公告
            OaNotify oaNotify = new OaNotify();
            oaNotify.setType("1");
            oaNotify.setTitle(unit + "-通过年检申报通知(点击下载通知书)");
            oaNotify.setStatus("1");
            oaNotify.setRemarks(fileName + ".jpg");
            //构建recordList
            List<OaNotifyRecord> recordList = new ArrayList<OaNotifyRecord>();
            OaNotifyRecord entity = new OaNotifyRecord();

            //设置记录信息
            entity.setId(IdGen.uuid());
            entity.setOaNotify(oaNotify);
            entity.setUser(recordUser);
            entity.setReadFlag("0");
            recordList.add(entity);
            oaNotify.setOaNotifyRecordList(recordList);

            //向经办人发送通过通知(电脑端)
            oaNotifyService.save(oaNotify);

            //手机微信推送通过通知
            resultTemplateMsgUtil.send3Word(openid, recordUser.getName() + "的经办人,您好,您提交的材料已审核通过.","年检申报",DateUtils.getDate(), DictUtils.getDictLabel("3", "check_flag", ""),"审批意见:" + "请登录电脑端，在“我的通告”中，点击下载打印通知书，并携带本通知书及其他年检材料前往区民政局驻区行政服务中心二楼5号窗口加盖公章，并办理年检手续。");
            mzbYearcheck.setUpdateDate(new Date());

            mzbYearcheck.setCheckRemarks(num);

        }
        //发送审核不通过的通知
        if (StringUtils.equals(mzbYearcheck.getStatus(),"4")) {
            resultTemplateMsgUtil.send3Word(openid, recordUser.getName() + "的经办人,您好,您提交的材料审核不通过.","年检申报", DateUtils.getDate(),DictUtils.getDictLabel("4", "check_flag", ""),"审批意见:" + mzbYearcheck.getRemarks());
        }


        //普通用户重新提交则状态变为再审核/***/
        if (!SecurityUtils.getSubject().isPermitted("mzb:mzbYearcheck:admin") && StringUtils.equals(mzbYearcheck.getStatus(),"4")) {
            mzbYearcheck.setStatus("5");
        }


        mzbYearcheckService.save(mzbYearcheck);
        addMessage(redirectAttributes, "保存年检申报成功");
        return "redirect:" + Global.getAdminPath() + "/mzb/mzbYearcheck/uncheck?repage";
    }

    private void genPdfFile(String fileName, Map paramMap) {

        Map<String, String> model1 = paramMap;
//		String result = FreeMarkers.renderString("hello ${userName}", model);
//		System.out.println(result);
//		// renderTemplate
        Configuration cfg = null;
        Template template = null;
        try {
            cfg = FreeMarkers.buildConfiguration("classpath:/");
            cfg.setDefaultEncoding("UTF-8");
            template = cfg.getTemplate("notification.html");

        } catch (IOException e) {
            e.printStackTrace();
        }

        String result2 = FreeMarkers.renderTemplate(template, model1);

        String content = result2;




        String fileDir = Global.getUserfilesBaseDir() +"htmlPdfFiles" + File.separator;

        String htmlFileName = fileName + ".html";
        String pdfFileName = fileName + ".jpg";
        String htmlFilePath = fileDir + htmlFileName;
        String pdfFilePath = fileDir + pdfFileName;

        //生成时间戳的html文件
        FileUtils.createFile(htmlFilePath);
        FileUtils.writeToFile(htmlFilePath, content,true);

        //调用wkhtmltopdf在原文件夹下面进行转换
        String execStr = "wkhtmltoimage " + htmlFilePath + " " + pdfFilePath;
        Runtime runtime=Runtime.getRuntime();
        try{
            runtime.exec(execStr);
        }catch(Exception e){
            System.out.println("Error!");
        }
    }


    @RequiresPermissions("mzb:mzbYearcheck:edit")
    @RequestMapping(value = "checked")
    public String checked(MzbYearcheck mzbYearcheck, Model model, RedirectAttributes redirectAttributes) {
        User recordUser = UserUtils.get(mzbYearcheck.getCreateBy().getId());
        //年检审核不通过
        if ("2".equals(mzbYearcheck.getStatus())) {
            String openid  = recordUser.getOpenid();
            resultTemplateMsgUtil.send2Word(openid, recordUser.getName() + "您好,您提交的材料未通过审核.","年检申报", DictUtils.getDictLabel("2", "check_flag", ""),"审批意见:" + mzbYearcheck.getRemarks());
        }
        //年检审核通过
        if ("3".equals(mzbYearcheck.getStatus())) {
            String openid  = recordUser.getOpenid();
            resultTemplateMsgUtil.send2Word(openid, recordUser.getName() + "您好,您提交的材料已通过审核.","年检申报", DictUtils.getDictLabel("3", "check_flag", ""),"审批意见:" + mzbYearcheck.getRemarks());
        }

        mzbYearcheckService.save(mzbYearcheck);
        addMessage(redirectAttributes, "审核年检申报成功");
        return "redirect:" + Global.getAdminPath() + "/mzb/mzbYearcheck/uncheck?repage";
    }


    @RequiresPermissions("mzb:mzbYearcheck:edit")
    @RequestMapping(value = "delete")
    public String delete(MzbYearcheck mzbYearcheck, RedirectAttributes redirectAttributes) {
        mzbYearcheckService.delete(mzbYearcheck);
        addMessage(redirectAttributes, "删除年检申报成功");
        return "redirect:" + Global.getAdminPath() + "/mzb/mzbYearcheck/uncheck?repage";
    }

}